<template>
  <div class="roles">
    <ToolBar  :show-all="false" :add-data="setAddDialogVisible" :delete-data="deleteById" :update-data="updateById" :show-multiple="false" ></ToolBar>
    <el-table
        border
        :data="tableData"
        row-key="id"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        :tree-props="{children:'rolesList',hasChildren:'hasChildren'}">
      <el-table-column
          type="index"
          label="编号"
          width="60">
      </el-table-column>
      <el-table-column
          prop="name"
          label="角色编码">
      </el-table-column>
      <el-table-column
          prop="introduction"
          label="角色名称">
      </el-table-column>
      <el-table-column
          prop="roleLevel"
          label="角色等级">
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime|formatDate }}
        </template>
      </el-table-column>

      <!--      <el-table-column-->
      <!--          label="其他信息"-->
      <!--          width="180">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-popover trigger="hover" placement="top">-->
      <!--            <p>创建者: {{ scope.row.createUser.name }}</p>-->
      <!--            <p>创建时间: {{ scope.row.createdTime|formatDate }}</p>-->
      <!--            <p>更新者: {{ scope.row.updateUser.name}}</p>-->
      <!--            <p>更新时间: {{ scope.row.updateTime|formatDate}}</p>-->
      <!--            <div slot="reference" class="name-wrapper">-->
      <!--              <el-tag size="medium">{{ scope.row.rolesname }}</el-tag>-->
      <!--            </div>-->
      <!--          </el-popover>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
          hide-on-single-page
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size=size
          layout="total, sizes, prev, pager, next, jumper"
          :total=total>
      </el-pagination>
    </div>
    <el-dialog :title="'角色'+operationType" :visible.sync="dialogFormVisible">
      <el-form :model="roleForm" ref="roleForm" :rules="roleFormRules">
        <el-form-item label="角色编码" :label-width="formLabelWidth" prop="name">
          <el-input v-model="roleForm.name" autocomplete="off" placeholder="如ROLE_ADMIN"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="introduction">
          <el-input v-model="roleForm.introduction" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色等级" :label-width="formLabelWidth" prop="roleLevel">
          <el-input v-model="roleForm.roleLevel" autocomplete="off" type="number"></el-input>
        </el-form-item>
        <el-form-item label="菜单分配"  :label-width="formLabelWidth">
          <el-cascader-panel :options="treeData"  :props="defaultProps" v-model="menuList" @change="handleDelete" :show-all-levels="false" :getCheckedNodes="true"></el-cascader-panel>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addData('roleForm')" v-if="operationType==='添加'">确定<span v-text="operationType"></span></el-button>
        <el-button type="primary" @click="updateData('roleForm')" v-if="operationType==='修改'">确定<span v-text="operationType"></span></el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ToolBar from "@/components/common/ToolBar";

export default {
  name: "Roles",
  components: {ToolBar},
  data() {
    return {
      currentPage: 1,
      total: 0,
      size: 10,
      tableData: [],
      dialogFormVisible: false,
      roleForm: {
        name: null,
        introduction: null,
        roleLevel:null,
        menuList:[]
      },
      formLabelWidth: "85px",
      operationType: "添加",
      roleFormRules: {
        name: [
          {
            required:true,message:"请输入角色编码...",trigger:"blur"
          }
        ],
        introduction: [
          {
            required:true,message:"请输入角色名称...",trigger:"blur"
          }
        ],
        roleLevel:[
          {
            required:true,message:"请输入角色等级,数字越大，等级越低...",trigger:"blur"
          }
        ]
      },
      filterText: null,
      treeData: [],
      defaultProps: {
        value:"id",
        children: 'menuList',
        label: 'menuName',
        multiple:true,
        // checkStrictly: true
      },
      data:[],
      menuList:[],
    }
  },
  created() {
    this.getDataList()
    this.getTreeDataList()
  },
  methods: {
    handleEdit(index, row) {
      this.menuList=[]
      console.log(index, row);
      this.operationType="修改"
      this.roleForm=row
      if(row.menuList!=null){
        row.menuList.forEach(item=>{
          console.log("MenuItem:",item)
          if(item!==null){
            this.menuList.push([item.pid,item.id])

          }
        })
      }else{
        this.menuList=[]
      }
      this.dialogFormVisible=true
      console.log("Menu:",this.menuList)
    },
    handleDelete(index, row) {
      console.log(index, row);
      console.log("已选菜单：",this.menuList)
    },
    getDataList() {
      axios.get("/roles/list/" + this.currentPage + "/" + this.size).then(res => {
        console.log("角色列表：", res)
        if (res.data.success) {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
          this.pages = res.data.data.pages
        }
      })
    },
    getTreeDataList() {
      axios.get("/menu/list/0").then(res => {
        console.log("菜单列表2：", res)
        if (res.data.success) {
          this.treeData = res.data.data
        }
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getDataList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getDataList()
    },
    setAddDialogVisible() {
      this.operationType = "添加"
      this.dialogFormVisible = true
      this.roleForm={}
      this.menuList=[]
      this.getTreeDataList()
    },
    deleteById() {
      console.log("角色删除")
    },
    updateById() {

      this.operationType=1
      this.dialogFormVisible=true
      this.getTreeDataList()
      console.log("角色修改")

    },

    addData(form) {

      const roleMenuList=[]
      this.menuList.forEach(item=>{
        item.forEach(child=>{
          roleMenuList.push({id:child})
        })

      })
      this.roleForm.menuList=roleMenuList
      console.log(this.roleForm)
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.roleForm.createUserId = this.$store.state.userInfo.id;
          axios.post("/roles/add", this.roleForm).then(res => {
            if(res.data.success){
              this.$tools.showMessage(res.data.message,"success")
              this.dialogFormVisible=false
              this.getDataList()
            }else{
              this.$tools.showMessage(res.data.message,"danger")
            }
          })
        } else {
          this.$tools.showMessage("请完善角色信息...", 'warning')
        }
      })
    },
    updateData(form){
      const roleMenuList=[]
      this.menuList.forEach(item=>{
        item.forEach(child=>{
          roleMenuList.push({id:child})
        })
      })
      const menuList=[...new Set(roleMenuList)]

      this.roleForm.menuList=roleMenuList
      console.log("RoleMenu:",menuList,",Length:",menuList.length)
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.roleForm.updateUserId = this.$store.state.userInfo.id;
          axios.post("/roles/update", this.roleForm).then(res => {
            if(res.data.success){
              this.$tools.showMessage(res.data.message,"success")
              this.dialogFormVisible=false
              this.getDataList()
            }else{
              this.$tools.showMessage(res.data.message,"danger")
            }
          })
        } else {
          this.$tools.showMessage("请完善角色信息...", 'warning')
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
